// const app = getApp()

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
// 字符串转byte
function stringToBytes(str) {
  var array = new Uint8Array(str.length);
  for (var i = 0, l = str.length; i < l; i++) {
    array[i] = str.charCodeAt(i);
  }
  console.log(array);
  return array.buffer;
}

Page({
  data: {
    devices: [],
    connected: false,
    conList: [],
    chs: [],
  },
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    
    return new Promise((resolve,reject)=>{
      if (this._discoveryStarted) {
        resolve(this.data.devices);
        return;
      }
      this._discoveryStarted = true;
      wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success: (res) => {
          console.log('startBluetoothDevicesDiscovery success', res);
          
          this.onBluetoothDeviceFound().then(devices=>{
            resolve(devices);
          })
        },
      })
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {
    return new Promise((resolve, reject) => {
      wx.onBluetoothDeviceFound((res) => {
        res.devices.forEach(device => {
          if (!device.name && !device.localName) {
            return
          }
          const foundDevices = this.data.devices
          const idx = inArray(foundDevices, 'deviceId', device.deviceId)
          const data = {}
          if (idx === -1) {
            data[`devices[${foundDevices.length}]`] = device
          } else {
            data[`devices[${idx}]`] = device
          }
          this.setData(data);
        })
      })
      resolve(this.data.devices);
    })
    
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    // let buffer = new ArrayBuffer(1)
    // let dataView = new DataView(buffer)
    // dataView.setUint8(0, Math.random() * 255 | 0)
    let buffer = stringToBytes("1")
    console.log("发送服务码：" + this._characteristicId)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
      success: function(res) {
        console.log("发送成功", res)
      },
      fail(res) {
        console.log("发送失败", res)
      }
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
  writeBLECharacteristicValue0() {
    // 向蓝牙设备发送一个0x00的16进制数据
    // let buffer = new ArrayBuffer(1)
    // let dataView = new DataView(buffer)
    // dataView.setUint8(0, Math.random() * 255 | 0)
    let buffer = stringToBytes("0")
    console.log("发送服务码：" + this._characteristicId)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
      success: function (res) {
        console.log("发送成功", res)
      },
      fail(res) {
        console.log("发送失败", res)
      }
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },


  //扫描全部蓝牙服务
  openBluetoothAll() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery().then(res=>{
          //console.log('扫描全部蓝牙服务', res);
          res.forEach(item=>{
            console.log('xxx',item);
          })
          this.openBluetoothConnect()
        })
        //console.log(this.data.devices);
        
        
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    });
   

    
    //循环每个蓝牙服务
    // this.data.devices.forEach( device => {
    //    console.log(device)
    //    console.log(111111111111111)

      // //连接每个蓝牙
      // wx.createBLEConnection({
      //   deviceId,
      //   success: (res) => {
      //     this.setData({
      //       connected: true,
      //       name,
      //       deviceId,
      //     })
      //     this.getBLEDeviceServices(deviceId)
      //   }
      // })

      // //发送数据
      // let buffer = stringToBytes("START")
      // console.log("发送服务码：" + this._characteristicId)
      // wx.writeBLECharacteristicValue({
      //   deviceId: this._deviceId,
      //   serviceId: this._serviceId,
      //   characteristicId: this._characteristicId,
      //   value: buffer,
      //   success: function (res) {
      //     console.log("发送成功", res)
      //   },
      //   fail(res) {
      //     console.log("发送失败", res)
      //   }
      // })
    // });
    
  },

  //给所有蓝牙连接
  openBluetoothConnect(){
    console.log(this.data.devices)
    if (this.data.devices.length > 0) {
      this.data.devices.forEach(device => {
          console.log(device.deviceId)
          const deviceId = device.deviceId
          const name = device.name
          wx.createBLEConnection({
            deviceId,
            success: (res) => {
              this.setData({
                connected: true,
                name,
                deviceId
              })
              this.getBLEDeviceServices(deviceId)
            }
          })
        this.setData({ conList: { 'name': name, 'deviceId': deviceId } })

        //给每个连接发送数据
        let buffer = stringToBytes("START")
        if (this._characteristicId == undefined) {
          return
        }
        console.log("发送服务码：" + this._characteristicId)
        wx.writeBLECharacteristicValue({
          deviceId: this._deviceId,
          serviceId: this._serviceId,
          characteristicId: this._characteristicId,
          value: buffer,
          success: function (res) {
            console.log("发送成功", res)
          },
          fail(res) {
            console.log("发送失败", res)
          }
        })

        })
        // this.conList.push({'name':name, 'deviceId': deviceId}) 
      this.stopBluetoothDevicesDiscovery()
        
        //console.log(this.conList)
    } else {
      console.log("没有发现蓝牙")
    }
  },
  //断开蓝牙
  openBluetoothClose() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },

  //分享页面
  onShareAppMessage: function (res) {
    var that = this;
    return {
      title: '蓝牙连接器',
      path: '/pages/index/index',
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})
